package com.candy.candyproduct.controller;

import com.candy.candycommon.utils.ResultBean;
import com.candy.candyproduct.bean.Product;
import com.candy.candyproduct.service.ProductService;
import com.candy.candyproductservice.dto.ProductDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author suYanLong
 * @date 2022年09月29日 13:36
 */
@Slf4j
@RestController
@RequestMapping("product")
@AllArgsConstructor
public class ProductController {

    public final ProductService productService;

    @GetMapping("getByOrderId")
    public ResultBean getByOrderId(@RequestParam Long orderId) {
        if (orderId == null) {
            return ResultBean.error("订单id不能为空！");
        }
        log.info("=============getByOrderId============");
        if (orderId.equals(1l)) {
            return ResultBean.ok("1111");
        }
        return ResultBean.ok("other orderId");
    }

    @PostMapping("subProduct")
    public ResultBean subProduct(@RequestBody ProductDTO productDTO) {
        // int i = 1 / 0; // 模拟异常
        productService.subProduct(productDTO);
        return ResultBean.ok();
    }

    @PostMapping("subProduct2")
    public void subProduct2(@RequestBody ProductDTO productDTO) {
        productService.subProduct(productDTO);
    }

    /**
     * 多线程批量插入【保证事务】
     *
     * @param num
     * @return
     */
    @GetMapping("batchAdd")
    @Transactional
    public ResultBean batchAdd(Integer num) {
        List<Product> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            Product product = new Product();
            product.setProName("ceshi" + i);
            product.setProNum(i);
            list.add(product);
        }
        return ResultBean.ok(productService.batchMultiThread(list));
    }

}
